/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
//双指针法
var removeNthFromEnd = function (head, n) {
  // 创建虚拟头节点
  let dummy = new ListNode(0)
  dummy.next = head

  let first = dummy
  let second = dummy

  //fisrt指针走n+1步
  for (let i = 0; i <= n; i++) {
    first = first.next
  }

  //当first指针非空时，first、second指针同时后移
  while (first) {
    first = first.next
    second = second.next
  }

  //删除second指针的后一个节点
  second.next = second.next ? second.next.next : null

  return dummy.next
};

// 一般方法
// var removeNthFromEnd = function (head, n) {
//   //统计链表的长度
//   let sz = 0
//   let tempNode = head
//   while (tempNode) {
//     sz++
//     tempNode = tempNode.next
//   }
//   tempNode = head

//   //计算要删除的元素是正数第几个
//   let index = sz + 1 - n
//   if (index === 1) {
//     return head.next
//   }

//   let count = 1
//   let beforeTemp = tempNode
//   tempNode = tempNode.next
//   while (tempNode) {
//     count++
//     if (index === count) {
//       beforeTemp.next = tempNode.next
//       tempNode.next = null
//       break
//     }
//     beforeTemp = tempNode
//     tempNode = tempNode.next
//   }

//   return head
// };